/*
 * @(#)FormData.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.dcivision.form.bean.FormData;
import com.dcivision.form.bean.FormElementType;
import com.dcivision.form.bean.FormFileAttachment;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.web.AbstractSearchForm;

/**
  FormDataDAObject.java

  This class is the data access bean for table "FORM_DATA".

  @author      Scott Tong
  @company     DCIVision Limited
  @creation date   07/01/2004
  @version     $Revision: 1.17.2.1 $
*/

public class FormDataDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.17.2.1 $";

  public static final String TABLE_NAME = "FORM_DATA";

  public FormDataDAObject(SessionContainer sessionContainer, Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  
  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("DATA_ELEMENT_ID");
    this.vecDBColumn.add("DATA_STRING");
    this.vecDBColumn.add("DATA_NUMERIC");
    this.vecDBColumn.add("DATA_DATETIME");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  
  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.DATA_ELEMENT_ID, A.DATA_STRING, A.DATA_NUMERIC, A.DATA_DATETIME, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_DATA A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          FormData tmpFormData = new FormData();
          tmpFormData.setID(getResultSetInteger(rs, "ID"));
          tmpFormData.setDataElementID(getResultSetInteger(rs, "DATA_ELEMENT_ID"));
          tmpFormData.setDataString(getResultSetString(rs, "DATA_STRING"));
          tmpFormData.setDataNumeric(getResultSetFloat(rs, "DATA_NUMERIC"));
          tmpFormData.setDataDatetime(getResultSetTimestamp(rs, "DATA_DATETIME"));
          tmpFormData.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormData.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormData.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormData.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormData.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));

          tmpFormData.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormData.setCreatorName(UserInfoFactory.getUserFullName(tmpFormData.getCreatorID()));
          tmpFormData.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormData.getUpdaterID()));
          return(tmpFormData);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  
  protected synchronized List getList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.DATA_ELEMENT_ID, A.DATA_STRING, A.DATA_NUMERIC, A.DATA_DATETIME, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_DATA A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 2, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 2, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormData tmpFormData = new FormData();
          tmpFormData.setID(getResultSetInteger(rs, "ID"));
          tmpFormData.setDataElementID(getResultSetInteger(rs, "DATA_ELEMENT_ID"));
          tmpFormData.setDataString(getResultSetString(rs, "DATA_STRING"));
          tmpFormData.setDataNumeric(getResultSetFloat(rs, "DATA_NUMERIC"));
          tmpFormData.setDataDatetime(getResultSetTimestamp(rs, "DATA_DATETIME"));
          tmpFormData.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormData.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormData.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormData.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormData.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormData.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormData.setCreatorName(UserInfoFactory.getUserFullName(tmpFormData.getCreatorID()));
          tmpFormData.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormData.getUpdaterID()));
          tmpFormData.setRecordCount(totalNumOfRecord);
          tmpFormData.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormData);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  
  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.DATA_ELEMENT_ID, A.DATA_STRING, A.DATA_NUMERIC, A.DATA_DATETIME, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_DATA A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        while (rs.next()) {
          FormData tmpFormData = new FormData();
          tmpFormData.setID(getResultSetInteger(rs, "ID"));
          tmpFormData.setDataElementID(getResultSetInteger(rs, "DATA_ELEMENT_ID"));
          tmpFormData.setDataString(getResultSetString(rs, "DATA_STRING"));
          tmpFormData.setDataNumeric(getResultSetFloat(rs, "DATA_NUMERIC"));
          tmpFormData.setDataDatetime(getResultSetTimestamp(rs, "DATA_DATETIME"));
          tmpFormData.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormData.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormData.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormData.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormData.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormData.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormData.setCreatorName(UserInfoFactory.getUserFullName(tmpFormData.getCreatorID()));
          tmpFormData.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormData.getUpdaterID()));
          result.add(tmpFormData);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  
  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
  }

  
  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
  }

  
  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  
  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    FormData tmpFormData = (FormData)((FormData)obj).clone();

    synchronized(dbConn) {
      try {
        Integer nextID = getNextPrimaryID();
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   FORM_DATA(ID, DATA_ELEMENT_ID, DATA_STRING, DATA_NUMERIC, DATA_DATETIME, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, nextID);
        setPrepareStatement(preStat, 2, tmpFormData.getDataElementID());
        /*
        setPrepareStatement(preStat, 3, tmpFormData.getDataString());
        setPrepareStatement(preStat, 4, tmpFormData.getDataNumeric());
        setPrepareStatement(preStat, 5, tmpFormData.getDataDatetime());
        */
       //Null String

       if(tmpFormData.getDataObject() instanceof String){
         setPrepareStatement(preStat, 3, (String)tmpFormData.getDataObject());
       }else{
         String nullStr=null;
         setPrepareStatement(preStat, 3, nullStr);
       }
       //Null Number
       if(tmpFormData.getDataObject() instanceof Number){
         setPrepareStatement(preStat, 4, (Float)tmpFormData.getDataObject());
       }else{
         Float nullNo=null;
         setPrepareStatement(preStat, 4, nullNo);
       }
       //Null Timestamp
       if(tmpFormData.getDataObject() instanceof java.util.Date){
         setPrepareStatement(preStat, 5, (java.sql.Timestamp)tmpFormData.getDataObject());
       }else{
         java.sql.Date nullDate = null;
         setPrepareStatement(preStat, 5, nullDate);
       }

        setPrepareStatement(preStat, 6, GlobalConstant.RECORD_STATUS_ACTIVE);
        setPrepareStatement(preStat, 7, new Integer(0));
        setPrepareStatement(preStat, 8, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 9, currTime);
        setPrepareStatement(preStat, 10, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 11, currTime);
        preStat.executeUpdate();
        tmpFormData.setID(nextID);
        tmpFormData.setCreatorID(sessionContainer.getUserRecordID());
        tmpFormData.setCreateDate(currTime);
        tmpFormData.setUpdaterID(sessionContainer.getUserRecordID());
        tmpFormData.setUpdateDate(currTime);
        tmpFormData.setUpdateCount(new Integer(0));
        tmpFormData.setCreatorName(UserInfoFactory.getUserFullName(tmpFormData.getCreatorID()));
        tmpFormData.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormData.getUpdaterID()));
        return(tmpFormData);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  
  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    FormData tmpFormData = (FormData)((FormData)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE FORM_DATA ");
        sqlStat.append("SET  DATA_ELEMENT_ID=?, DATA_STRING=?, DATA_NUMERIC=?, DATA_DATETIME=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpFormData.getDataElementID());
        setPrepareStatement(preStat, 2, tmpFormData.getDataString());
        setPrepareStatement(preStat, 3, tmpFormData.getDataNumeric());
        setPrepareStatement(preStat, 4, tmpFormData.getDataDatetime());
        setPrepareStatement(preStat, 5, new Integer(tmpFormData.getUpdateCount().intValue() + 1));
        setPrepareStatement(preStat, 6, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 7, currTime);
        setPrepareStatement(preStat, 8, tmpFormData.getID());
        setPrepareStatement(preStat, 9, tmpFormData.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpFormData.setUpdaterID(sessionContainer.getUserRecordID());
          tmpFormData.setUpdateDate(currTime);
          tmpFormData.setUpdateCount(new Integer(tmpFormData.getUpdateCount().intValue() + 1));
          tmpFormData.setCreatorName(UserInfoFactory.getUserFullName(tmpFormData.getCreatorID()));
          tmpFormData.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormData.getUpdaterID()));
          return(tmpFormData);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  
  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    FormData tmpFormData = (FormData)((FormData)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   FORM_DATA ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpFormData.getID());
        setPrepareStatement(preStat, 2, tmpFormData.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return(tmpFormData);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  
  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    FormData tmpFormData = (FormData)this.oldValue;

    if (tmpFormData != null) {
      oldValues.add(toAuditTrailValue(tmpFormData.getID()));
      oldValues.add(toAuditTrailValue(tmpFormData.getDataElementID()));
      oldValues.add(toAuditTrailValue(tmpFormData.getDataString()));
      oldValues.add(toAuditTrailValue(tmpFormData.getDataNumeric()));
      oldValues.add(toAuditTrailValue(tmpFormData.getDataDatetime()));
      oldValues.add(toAuditTrailValue(tmpFormData.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpFormData.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpFormData.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpFormData.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpFormData.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpFormData.getUpdateDate()));
    }

    tmpFormData = (FormData)obj;
    if (tmpFormData != null) {
      newValues.add(toAuditTrailValue(tmpFormData.getID()));
      newValues.add(toAuditTrailValue(tmpFormData.getDataElementID()));
      newValues.add(toAuditTrailValue(tmpFormData.getDataString()));
      newValues.add(toAuditTrailValue(tmpFormData.getDataNumeric()));
      newValues.add(toAuditTrailValue(tmpFormData.getDataDatetime()));
      newValues.add(toAuditTrailValue(tmpFormData.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpFormData.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpFormData.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpFormData.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpFormData.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpFormData.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/
  /**
   * get FormData object by DataElementID
   * @param dataElementID
   * @return FormData object
   * @throws ApplicationException
   */
  public synchronized AbstractBaseObject getByDataElementID(Integer dataElementID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.DATA_ELEMENT_ID, A.DATA_STRING, A.DATA_NUMERIC, A.DATA_DATETIME, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_DATA A ");
        sqlStat.append("WHERE  A.DATA_ELEMENT_ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, dataElementID);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          FormData tmpFormData = new FormData();
          tmpFormData.setID(getResultSetInteger(rs, "ID"));
          tmpFormData.setDataElementID(getResultSetInteger(rs, "DATA_ELEMENT_ID"));
          tmpFormData.setDataString(getResultSetString(rs, "DATA_STRING"));
          tmpFormData.setDataNumeric(getResultSetFloat(rs, "DATA_NUMERIC"));
          tmpFormData.setDataDatetime(getResultSetTimestamp(rs, "DATA_DATETIME"));
          tmpFormData.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormData.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormData.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormData.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormData.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormData.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormData.setCreatorName(UserInfoFactory.getUserFullName(tmpFormData.getCreatorID()));
          tmpFormData.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormData.getUpdaterID()));
          return(tmpFormData);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  public synchronized void deleteListByFormElementDataID(String[] idAry) throws ApplicationException {
    if (this.isSoftDeleteEnabled) {
      this.softDeleteListByFormElementDataID(idAry);
    } else {
      this.hardDeleteListByFormElementDataID(idAry);
    }
  }
  
  protected void softDeleteListByFormElementDataID(String[] idAry) throws ApplicationException {
    this.updateStatusByFormElementDataID(idAry, GlobalConstant.RECORD_STATUS_INACTIVE);
  }

  protected void hardDeleteListByFormElementDataID(String[] idAry) throws ApplicationException {
    if (idAry==null || idAry.length==0) {
      return;
    }

    StringBuffer sqlStat = new StringBuffer("DELETE FROM FORM_DATA WHERE DATA_ELEMENT_ID = " + idAry[0]);
    for (int i = 1; i < idAry.length; i++) {
      sqlStat.append(" OR DATA_ELEMENT_ID=" + idAry[i]);
    }

    PreparedStatement preStat = null;

    synchronized(dbConn) {
      try {
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        preStat.executeUpdate();
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e, e.toString());
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  private void updateStatusByFormElementDataID(String[] idAry, String status) throws ApplicationException {
    if (idAry==null || idAry.length==0) {
      return;
    }

    StringBuffer sqlStat = new StringBuffer("UPDATE FORM_DATA SET RECORD_STATUS='" + status + "', UPDATE_DATE=?, UPDATER_ID=? WHERE DATA_ELEMENT_ID=" + idAry[0]);
    for (int i = 1; i < idAry.length; i++) {
      sqlStat.append(" OR DATA_ELEMENT_ID=" + idAry[i]);
    }

    PreparedStatement preStat = null;

    synchronized(dbConn) {
      try {
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, Utility.getCurrentTimestamp());
        this.setPrepareStatement(preStat, 2, sessionContainer==null ? new Integer(0) : sessionContainer.getUserRecordID());
        preStat.executeUpdate();
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e, e.toString());
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  public synchronized List getDataValueListBySubmissionIDElementIDSeq(      
      Integer submissionID,
      Integer elementID,
      Integer seq)
      throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();
    synchronized(dbConn) {
      try {       
        sqlStat.append("SELECT B.ID, B.DATA_ELEMENT_ID, S.ID SECTION_ID, S.TITLE, C.FIELD_NAME, C.ELEMENT_TYPE, B.DATA_STRING, F.LABEL, B.DATA_NUMERIC, B.DATA_DATETIME, B.RECORD_STATUS, B.UPDATE_COUNT, B.CREATOR_ID, B.CREATE_DATE, B.UPDATER_ID, B.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_DATA_ELEMENT A INNER JOIN FORM_DATA B ON A.ID = B.DATA_ELEMENT_ID ");
        sqlStat.append("INNER JOIN FORM_ELEMENT C ON C.ID = A.ELEMENT_ID ");
        sqlStat.append("INNER JOIN MTM_FORM_SECTION_FORM_ELEMENT MS ON MS.ELEMENT_ID = C.ID ");
        sqlStat.append("INNER JOIN FORM_SECTION S ON MS.SECTION_ID = S.ID ");
        sqlStat.append("LEFT JOIN FORM_SELECTION_FIELD E ON E.ELEMENT_ID = A.ELEMENT_ID ");
        sqlStat.append("LEFT JOIN FORM_SELECTION_FIELD_OPTION F ON E.ID = F.SELECTION_FIELD_ID AND B.DATA_STRING = F.START_VALUE ");
        sqlStat.append("WHERE A.SUBMISSION_ID =? AND A.ELEMENT_ID = ? AND A.SEQ = ? ");   
        // sqlStat.append("ORDER BY A.SECTION_SEQ, A.ELEMENT_SEQ ");

        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);        
        this.setPrepareStatement(preStat, 1, submissionID);
        this.setPrepareStatement(preStat, 2, elementID);
        this.setPrepareStatement(preStat, 3, seq);

        rs = preStat.executeQuery();

        String elementType = null;
        String tmpStr1 = "";
        String tmpStr2 = "";
        FormData tempFormData = new FormData();
        boolean isSecond = false;
        FormFileAttachmentDAObject formFileAttachDAO = new FormFileAttachmentDAObject(sessionContainer,dbConn);
        
        String dataString="",valueString = "";
        String elementName="",sectionName="";
        Integer sectionID=new Integer("0");
        FormData formData = new FormData();
        int k=0;
        while(rs.next()){
        	sectionID=(getResultSetInteger(rs, "SECTION_ID").equals(sectionID) ? sectionID : getResultSetInteger(rs, "SECTION_ID"));
        	sectionName=(getResultSetString(rs, "TITLE").equals(sectionName) ? sectionName : getResultSetString(rs, "TITLE"));
        	elementName=(getResultSetString(rs, "FIELD_NAME").equals(elementName) ? elementName : getResultSetString(rs, "FIELD_NAME"));
        	elementType=(getResultSetString(rs, "ELEMENT_TYPE").equals(elementType) ? elementType : getResultSetString(rs, "ELEMENT_TYPE"));
        	if(k==0){
        		dataString=("").equals(getResultSetString(rs, "DATA_STRING")) ? dataString : getResultSetString(rs, "DATA_STRING");
        	}else{
        	dataString=("").equals(getResultSetString(rs, "DATA_STRING")) ? dataString : dataString + ","+ getResultSetString(rs, "DATA_STRING");
        	}
        	k++;
        	formData.setSectionID(sectionID);
          formData.setSectionName(sectionName);
          formData.setElementName(elementName);
          formData.setDataString("");
          log.debug(formData.getSectionID());
          log.debug(formData.getSectionName());
          log.debug(formData.getElementName());
          log.debug(dataString);
          log.debug(elementType);

          if(FormElementType.isSelection(elementType)){
            formData.setDataString(getResultSetString(rs, "LABEL"));

            if(FormElementType.ELEMENT_CHECK_BOX.equals(elementType) ){

              if(!isSecond){
                tempFormData = formData;
                isSecond = true;
              } else {
                  if(!Utility.isEmpty(tempFormData.getDataString())){
                    tmpStr1 = tempFormData.getDataString() + ";";
                  }
                  if(!Utility.isEmpty(formData.getDataString())){
                    tmpStr2 = formData.getDataString();
                  }
                  tempFormData.setDataString(tmpStr1 + tmpStr2);
              }
            } else {
              //result.add(formData);
            }
          }else if(FormElementType.ELEMENT_FILE.equals(elementType) ){
            List tmpAttachmentList = formFileAttachDAO.getFormFileAttachmentListByFormDataElementID(getResultSetInteger(rs, "ID"));
            if (!Utility.isEmpty(tmpAttachmentList)){
              for (int i=0; i<tmpAttachmentList.size(); i++) {
                FormFileAttachment attachment = (FormFileAttachment)tmpAttachmentList.get(i);  
                valueString += attachment.getAttachmentName() + ";";               
              }
            }          
            formData.setDataString(valueString);            
            //result.add(formData);
          }else if(FormElementType.ELEMENT_CURRENT_DATE.equals(elementType) || FormElementType.ELEMENT_DATE_PICKER.equals(elementType) ){
            formData.setDataString(!Utility.isEmpty(dataString) ? dataString.substring(0,10) :"");            
            //result.add(formData);
          }else{            
            formData.setDataString(dataString);            
            //result.add(formData);
          }
        }
        if(!Utility.isEmpty(tempFormData) && tempFormData.getSectionID()!=null){
          result.add(tempFormData);
        }
        result.add(formData);//sliever.hu.add
        return(result);

      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  public synchronized List getDataValueListBySubmissionIDElementIDDataElementSeq(      
        Integer submissionID,
        Integer elementID,
        Integer DataElementSeq)
        throws ApplicationException {
      PreparedStatement preStat = null;
      ResultSet rs = null;
      StringBuffer sqlStat = new StringBuffer();
      List result = new ArrayList();
      synchronized(dbConn) {
        try {       
          sqlStat.append("SELECT B.ID, B.DATA_ELEMENT_ID, S.ID SECTION_ID, S.TITLE, C.FIELD_NAME, C.ELEMENT_TYPE, B.DATA_STRING, F.LABEL, B.DATA_NUMERIC, B.DATA_DATETIME, B.RECORD_STATUS, B.UPDATE_COUNT, B.CREATOR_ID, B.CREATE_DATE, B.UPDATER_ID, B.UPDATE_DATE ");
          sqlStat.append("FROM   FORM_DATA_ELEMENT A, FORM_DATA B, FORM_ELEMENT C, FORM_SECTION S, MTM_FORM_SECTION_FORM_ELEMENT MS ");
          sqlStat.append("LEFT JOIN FORM_SELECTION_FIELD E ON E.ELEMENT_ID = A.ELEMENT_ID ");
          sqlStat.append("LEFT JOIN FORM_SELECTION_FIELD_OPTION F ON E.ID = F.SELECTION_FIELD_ID AND B.DATA_STRING = F.START_VALUE ");
          sqlStat.append("WHERE A.ID = B.DATA_ELEMENT_ID AND C.ID = A.ELEMENT_ID ");
          sqlStat.append("AND MS.ELEMENT_ID = C.ID AND MS.SECTION_ID = S.ID ");
          sqlStat.append("AND A.SUBMISSION_ID =? AND A.ELEMENT_ID = ? AND A.SEQ = ? ");   
          // sqlStat.append("ORDER BY A.SECTION_SEQ, A.ELEMENT_SEQ ");

          preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);        
          this.setPrepareStatement(preStat, 1, submissionID);
          this.setPrepareStatement(preStat, 2, elementID);
          // this.setPrepareStatement(preStat, 3, elementSeq);
          this.setPrepareStatement(preStat, 3, DataElementSeq);

          rs = preStat.executeQuery();

          String elementType = null;
          String tmpStr1 = "";
          String tmpStr2 = "";
          FormData tempFormData = new FormData();
          boolean isSecond = false;
          FormFileAttachmentDAObject formFileAttachDAO = new FormFileAttachmentDAObject(sessionContainer,dbConn);
          
          while (rs.next()) {          
            FormData formData = new FormData();
            String valueString = "";
            formData.setSectionID(getResultSetInteger(rs, "SECTION_ID"));
            formData.setSectionName(getResultSetString(rs, "TITLE"));
            formData.setElementName(getResultSetString(rs, "FIELD_NAME"));
            formData.setDataString("");
            elementType = getResultSetString(rs, "ELEMENT_TYPE");
            
            if(FormElementType.isSelection(elementType)){
              formData.setDataString(getResultSetString(rs, "LABEL"));

              if(FormElementType.ELEMENT_CHECK_BOX.equals(elementType) ){

                if(!isSecond){
                  tempFormData = formData;
                  isSecond = true;
                } else {
                    if(!Utility.isEmpty(tempFormData.getDataString())){
                      tmpStr1 = tempFormData.getDataString() + ";";
                    }
                    if(!Utility.isEmpty(formData.getDataString())){
                      tmpStr2 = formData.getDataString();
                    }
                    tempFormData.setDataString(tmpStr1 + tmpStr2);
                }
              } else {
                result.add(formData);
              }
            }else if(FormElementType.ELEMENT_FILE.equals(elementType) ){
              List tmpAttachmentList = formFileAttachDAO.getFormFileAttachmentListByFormDataElementID(getResultSetInteger(rs, "ID"));
              if (!Utility.isEmpty(tmpAttachmentList)){
                for (int i=0; i<tmpAttachmentList.size(); i++) {
                  FormFileAttachment attachment = (FormFileAttachment)tmpAttachmentList.get(i);  
                  valueString += attachment.getAttachmentName() + ";";               
                }
              }          
              formData.setDataString(valueString);            
              result.add(formData);
            }else{
              formData.setDataString(getResultSetString(rs, "DATA_STRING"));            
              result.add(formData);
            }
          }
          if(!Utility.isEmpty(tempFormData) && tempFormData.getSectionID()!=null){
            result.add(tempFormData);
          }
          return(result);

        } catch (ApplicationException appEx) {
          throw appEx;
        } catch (SQLException sqle) {
          log.error(sqle, sqle);
          throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
        } catch (Exception e) {
          log.error(e, e);
          throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
        } finally {
          try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
          try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        }
      }
    }
}
